import React, { useEffect, useState } from 'react';
import { Modal, Input, Form, Button, message } from 'antd';
import CaptchaFormItem from '@/components/CaptchaFormItem'
import styles from './index.module.scss';
import { captcha, emailCode, repassword } from '@/service'
import { v4 as uuidv4 } from 'uuid';
import { useTranslation } from 'react-i18next';


export default (props) => {
  const { t } = useTranslation();
  const { visible, onClose } = props;
  const [uuid, setUuid] = useState('');
  const [captchaUrl, setCaptchaUrl] = useState('');
  const [messageApi, contextHolder] = message.useMessage();
  const [countdown, setCountdown] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [form] = Form.useForm(); // 创建表单实例
  const onSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (values.email) {
        values.email = values.email.replace(/\s+/g, '');
      }
      const res = await repassword({ email: values.email, code: values.code, oldPassword: values.oldPassword, password: values.password, repassword: values.repassword });
      const { code, message } = res || {};
      if (code === 0) {
        messageApi.open({
          type: 'success',
          content: message
        });
        handleClose();
      } else {
        messageApi.open({
          type: 'error',
          content: message
        });
      }
    } catch (error) {
      if (error?.message) {
        messageApi.open({
          type: 'error',
          content: error?.message
        });
      }
    }
  }
  const validateEmail = (rule, value) => {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!value) {
      return Promise.reject(new Error(t('common.modal.Emailplacehoder')));
    }
    else if (!emailRegex.test(value.trim())) {
      return Promise.reject(new Error(t('common.modal.correctEmailplacehoder')));
    }
    return Promise.resolve();
  };
  const validateCaptCha = (rule, value) => {
    if (!value) {
      return Promise.reject(new Error(t('common.modal.verificationCodeplacehoder')));
    }
    return Promise.resolve();
  };
  const handleVerify = () => {
    const newUuid = uuidv4().replace(/-/g, '').substring(0, 32);
    setUuid(newUuid);
    fetchCaptcha(newUuid);
  };
  const handleClose = () => {
    onClose();
    form.resetFields();
    setCountdown(0);
  }
  const fetchCaptcha = async (uuid) => {
    try {
      let params = { uuid };
      const response = await captcha(params);
      const imageUrl = URL.createObjectURL(response);
      setCaptchaUrl(imageUrl);
    } catch (error) {
      console.error('Error fetching captcha:', error);
    }
  };
  const getEmailCode = async () => {
    if (countdown > 0) return;
    try {
      setIsLoading(true);
      let params = {
        uuid: uuid,
        email: form.getFieldValue('email').trim() || '',
        captcha: form.getFieldValue('captcha') || ''
      };
      const response = await emailCode(params);
      const { code, message } = response || {};
      if (code === 0) {
        messageApi.open({
          type: 'success',
          content: message
        });
        setCountdown(60);
      } else {
        messageApi.open({
          type: 'error',
          content: message
        });
      }
    } catch (error) {
      messageApi.open({
        type: 'error',
        content: error?.message,
      });
    } finally {
      setIsLoading(false);
    }
  };
  // 启动倒计时逻辑
  useEffect(() => {
    let timer;
    if (countdown > 0) {
      timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
    }
    return () => clearTimeout(timer);
  }, [countdown]);
  useEffect(() => {
    const initialUuid = uuidv4().replace(/-/g, '').substring(0, 32);
    setUuid(initialUuid);
    fetchCaptcha(initialUuid);
  }, []);
  return (
    <Modal
      title={t('header.userSetting')}
      open={visible}
      onCancel={handleClose}
      className='custom-notitle-modal'
      width={650}
      destroyOnClose
      maskClosable={false}
      footer={null}
    >
      <Form
        form={form}
        name="Password_form"
        className={`custom-form-primary ${styles.psdform}`}
        labelCol={{ span: 7 }}
        wrapperCol={{ span: 12 }}
        autoComplete="new-password"
      >
        <Form.Item
          label={t('header.user.email')}
          name="email"
          rules={[
            {
              required: true,
              validator: validateEmail,
            },
          ]}
        >
          <Input type="text" placeholder={t('common.modal.enterPlacehoder')} />
        </Form.Item>

        <Form.Item
          label={t('common.modal.label.verificationCode')}
          name="captcha"
          rules={[
            {
              required: true,
              validator: validateCaptCha,
            },
          ]}
        >
          <CaptchaFormItem onVerify={handleVerify} captchaUrl={captchaUrl} />
        </Form.Item>
        <Form.Item
          label={t('common.modal.label.emailCode')}
          name="code"
          rules={[
            {
              required: true,
              message: t('common.modal.emailverificationCodeplacehoder'),
            },
          ]}
        >
          <Input
            placeholder={t('common.modal.enterPlacehoder')}
            addonAfter={
              <Button
                type="link"
                onClick={getEmailCode}
                disabled={countdown > 0 || isLoading}
              >
                {countdown > 0 ? `${countdown}s` : t('common.modal.getEmailCodeBtn')}
              </Button>
            }
          />
        </Form.Item>
        <Form.Item
          label={t('common.modal.label.passward')}
          name="oldPassword"
          rules={[{ required: true, message: t('common.modal.passwordplacehoder') }]}
        >
          <Input.Password autoComplete="new-password" placeholder={t('common.modal.enterPlacehoder')} />
        </Form.Item>
        <Form.Item
          label={t('common.modal.label.passwardNew')}
          name="password"
          rules={[{ required: true, message: t('common.modal.newPasswordplacehoder') }]}
        >
          <Input.Password autoComplete="new-password" placeholder={t('common.modal.enterPlacehoder')} />
        </Form.Item>
        <Form.Item
          label={t('common.modal.label.reEnter')}
          name="repassword"
          rules={[
            { required: true, message: t('common.modal.newPasswordReplacehoder') },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error(t('common.modal.passwordinconsistencyPlacehoder')));
              },
            }),
          ]}
        >
          <Input.Password  autoComplete="new-password" placeholder={t('common.modal.enterPlacehoder')} />
        </Form.Item>
        <div className={styles.btnGroup}>
          <Form.Item noStyle>
            <Button className={styles.cancelBtn} onClick={handleClose}>
              {t('common.modal.button.cancel')}
            </Button>
            <Button type='primary' htmlType="submit" onClick={onSubmit}>
              {t('common.modal.button.submit')}
            </Button>
          </Form.Item>
        </div>
      </Form>
      {contextHolder}
    </Modal>
  );
}
